import * as bugsService from '../services/bugs'
import moment from 'moment'

export default {
  namespace: 'bugs',
  state: {
    list: []
  },
  reducers: {
    save(state, { payload: { results: list , count, values} }) {
      return { ...state, list, count, values };
    },
  },
  effects: {
    *fetch({payload: values}, { call, put }) {
      const { data } = yield call(bugsService.fetch, values);
      const { results, count } = data;
      yield put({
        type: 'save',
        payload: {
          results,
          count,
          values
        },
      });
    },
    *patch({ payload: { id, values } }, { call, put }) {
      values.solveTime = moment()
      yield call(bugsService.patch, id, values);
      yield put({ type: 'fetch' });
    },
    *create({ payload: values }, { call, put }) {
      yield call(bugsService.create, values);
      yield put({ type: 'fetch' });
    },
  },
  subscriptions: {
    setup({dispatch, history}) {
      return history.listen(({pathname}) => {
        if (pathname === '/bugs') {
          dispatch({type: 'fetch', payload: null});
        }
      });
    },
  },
};
